package com.firstProject.controller;

import com.firstProject.Dao.DeviceRealDataDao;
import com.firstProject.model.Device;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class MapController {
    Gson gson = new Gson();

    @Autowired
    private DeviceRealDataDao dao;

    @RequestMapping(value = "map",produces = "application/text;charset=utf-8")
    public String deviceMap(HttpServletRequest rqs){
        rqs.setAttribute("projects",getMessage());
        return "index";
    }

    @RequestMapping(value = "refresh" ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public List<Device> realData_device(){
        List<Device> devices = dao.deviceRealData();
        return devices;
    }

    public List<Map<String, String>> getMessage(){
        String url = "http://192.168.0.222:3000/";
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"utf-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        }catch (MalformedURLException e){
        }catch (IOException e){
        }
        //String sss = " [{\"id\": 1, \"name\": \"车载工程系统\", \"projectId\": 1000},{\"id\": 2, \"name\": \"仓库工程系统\", \"projectId\": 2000} ] ";
        List<Map<String, String>> list = gson.fromJson(json.toString(),new TypeToken<List<Map<String, String>>>(){}.getType());
        if(list==null){
            return new ArrayList<Map<String, String>>();
        }
        for(Map<String,String> map : list){
            //String id = String.valueOf(map.get("id"));
            Double d = Double.parseDouble(map.get("id"));
            int id = (int)(d+0);
            map.put("id",String.valueOf(id));
            d = Double.parseDouble(map.get("projectId"));
            int pid = (int)(d+0);
            map.put("projectId", String.valueOf(pid));
        }
        return list;
    }

}
